//
//  YKTaskUtil.m
//  YK_BaseTools
//
//  Created by edward on 2020/2/23.

#import "YKTaskUtil.h"

@interface YKTaskUtil()

@property (nonatomic, strong) NSMutableArray *tasks;

@property (nonatomic, assign) NSInteger currentIndex;
///
@property (nonatomic, assign) NSInteger saveIndedx;
    
@end

@implementation YKTaskUtil

- (void)executeFirstTask
{
    self.currentIndex = 0;
    self.saveIndedx = 0;
    [self nextTask];
}

- (void)nextTask
{
    if (self.currentIndex > self.tasks.count - 1) {
        return;
    }
    NSDictionary *task = self.tasks[self.currentIndex];
    void(^block)(void) = task[@"block"];
    dispatch_async(dispatch_get_main_queue(), ^{    
        if (block) {
            block();
        }
    });
    self.saveIndedx = self.currentIndex;
    self.currentIndex++;
}

- (void)rollbackOneStep
{
    if (self.currentIndex <= 0) {
        return;
    }
    self.currentIndex = self.saveIndedx;
}

- (void)addBlock:(void(^)(void))block priority:(NSInteger)priority
{
    if (block) {
        [self.tasks addObject:@{@"block":block,@"priority":@(priority)}];
        [self.tasks sortUsingComparator:^NSComparisonResult(NSDictionary * _Nonnull obj1, NSDictionary * _Nonnull obj2) {
            return [obj1[@"priority"] integerValue] < [obj2[@"priority"] integerValue];
        }];
    }
}

- (void)executeTaskWithPriority:(NSInteger)priority
{
    [self.tasks enumerateObjectsUsingBlock:^(NSDictionary *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj[@"priority"] intValue] == priority) {
            void(^block)(void) = obj[@"block"];
            if (block) {
                block();
            }
            *stop=YES;
            return;
        }
    }];
}

- (void)clearTask
{
    [self.tasks removeAllObjects];
    self.currentIndex = 0;
    self.saveIndedx = 0;
}

- (NSMutableArray *)tasks
{
    if (!_tasks) {
        _tasks = [NSMutableArray array];
    }
    return _tasks;
}
@end
